<template>
  <div class="home-child">
    <div class="line" v-if="start">
      <span>
        任务状态：下载中
      </span>
      <span></span>
    </div>
    <div class="line" v-if="!start">
      <span>
        安装位置：<span :class="{ 'shake-bottom': installPath, }">{{ installAddress }}</span>
      </span>
      <button @click=" installOrDownload('i'); selectPath()">浏览</button>
    </div>
    <div class="line" v-if="!start">
      <span>
        下载位置：<span :class="{ 'shake-bottom': downloadPath }">{{ downloadAddress }}</span>
      </span>
      <button @click=" installOrDownload('d'); selectPath()">浏览</button>
    </div>
    <div class="line">
      <span>
        下载线路：{{ operator }}
      </span>
      <span></span>
    </div>
    <div class="line">
      <span>
        预计时间：{{ loadRemainingTime }}
      </span>
      <span></span>
    </div>
    <div class="line">
      <span>
        下载速度：{{ loadSpeed }} &nbsp;<span style="font-size: 12px;color:coral;position: relative; top: -3px;">{{
          accelerate }}</span>
      </span>
      <span></span>
    </div>
    <div class="line">
      <span>
        下载进度：{{ received }}{{ total }}
      </span>
      <span></span>
    </div>
    <div class="progress">
      <el-progress :text-inside="true" :percentage="percentage" :stroke-width="20" status="success"
        stroke-linecap="square" striped striped-flow :duration="duration" color="#05967e" />
    </div>
    <div class="progress-text" v-if="start">
      <h5 v-if="percentage < 100">正在提速加载中</h5>
      <h5 v-if="percentage >= 100">下载完成</h5>
      <svg t="1723212013365" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
        p-id="9008" width="16" height="16">
        <path
          d="M508.342857 102.4C281.6 102.4 96.914286 287.085714 96.914286 513.828571s184.685714 411.428571 411.428571 411.428572 411.428571-184.685714 411.428572-411.428572C919.771429 285.257143 735.085714 102.4 508.342857 102.4z m7.314286 367.542857h153.6L460.8 826.514286l54.857143-296.228572H347.428571L572.342857 201.142857l-56.685714 268.8z"
          fill="#F9BF55" p-id="9009"></path>
      </svg>
    </div>
    <div class="line">
      <div class="radio-box">
        <div class="radio-but" @click="openChildWindow()">
          <svg v-show="radioSwitch" t="1723208393153" class="icon" viewBox="0 0 1024 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="5084" width="10" height="10">
            <path
              d="M64.132646 496.564449l57.085136-54.933123L383.858528 664.712077c0 0 195.159842-180.534749 552.393989-479.748459l23.016203 57.541531c0 0-297.774941 287.705608-576.84896 594.112136L64.132646 496.564449z"
              p-id="5085"></path>
          </svg>
        </div>
        &nbsp;安装完成自动删除安装包
      </div>
    </div>

    <div class="line">
      <div class="radio-box">
        <div class="radio-but" @click="openChildWindow()">
          <svg v-show="radioSwitch" t="1723208393153" class="icon" viewBox="0 0 1024 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="5084" width="10" height="10">
            <path
              d="M64.132646 496.564449l57.085136-54.933123L383.858528 664.712077c0 0 195.159842-180.534749 552.393989-479.748459l23.016203 57.541531c0 0-297.774941 287.705608-576.84896 594.112136L64.132646 496.564449z"
              p-id="5085"></path>
          </svg>
        </div>
        &nbsp;兼容模式下载&nbsp;
        <svg t="1723208962173" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
          p-id="6248" width="15" height="15">
          <path
            d="M512 0a512 512 0 1 1 0 1024A512 512 0 0 1 512 0z m0 861.888a68.288 68.288 0 1 0 0-136.576 68.288 68.288 0 0 0 0 136.576z m186.56-379.648c29.952-43.904 41.088-82.304 40.96-136.192-0.128-84.864-80.256-174.976-200.96-174.976-128.64 0-253.696 63.744-253.696 227.2l113.28 0.384c0-55.808 36.032-114.944 113.024-114.944 46.08 0 112.64 18.624 112.64 86.72 0 62.656-20.48 75.456-81.92 120.32-59.328 40.32-89.6 92.992-87.424 158.08v33.664h115.584c0-102.912 72.768-115.392 128.512-200.32z"
            fill="#2c2c2c" p-id="6249"></path>
        </svg>
      </div>
    </div>

    <div class="line">
      <div class="radio-box">
        <div class="radio-but" @click="openChildWindow()">
          <svg v-show="radioSwitch" t="1723208393153" class="icon" viewBox="0 0 1024 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="5084" width="10" height="10">
            <path
              d="M64.132646 496.564449l57.085136-54.933123L383.858528 664.712077c0 0 195.159842-180.534749 552.393989-479.748459l23.016203 57.541531c0 0-297.774941 287.705608-576.84896 594.112136L64.132646 496.564449z"
              p-id="5085"></path>
          </svg>
        </div>
        &nbsp;下载完成自动关机
      </div>
    </div>

    <div class="download">
      <button v-if="!start && percentage < 100" @click="throttledStartDownload">开始下载</button>
      <button v-if="!start && percentage < 100" @click="throttledToClose">取消下载</button>
      <button v-if="start && !clickPauseDownload && percentage < 100" @click="throttledPause">暂停下载</button>
      <button v-if="start && clickPauseDownload && percentage < 100" @click="throttledResume"> 恢复下载</button>
      <button v-if="start && percentage < 100" @click="throttledCancel">取消下载</button>
      <button class="finish" v-if="percentage >= 100" @click="throttledToClose">下载完成</button>
    </div>

  </div>
</template>

<script setup lang="ts">
import { computed, watch, ref } from 'vue'
import throttle from 'lodash/throttle';

let installAddress = ref('请选择安装位置')
let downloadAddress = ref('请选择下载位置')
let I0RD = ref(true)
function installOrDownload(el: string) {
  el === 'i' ? I0RD.value = true : I0RD.value = false
}
async function selectPath() {
  let res = await window.myApi.selectPath('select')
  const containsChinese = /[\u4e00-\u9fa5]/.test(res);
  if (containsChinese) {
    alert('路径选择结果中包含中文字符，请选择不包含中文的路径。');
    return;
  }
  if (I0RD.value) {
    installAddress.value = res
  }
  else {
    downloadAddress.value = res
  }
}

let radioSwitch = ref(false);
function openChildWindow() {
  radioSwitch.value = !radioSwitch.value;
}




const percentage = ref<number>(0);
const loadSpeed = ref<string>('准备计算');
const accelerate = ref<string>('');
const loadRemainingTime = ref<string>('准备计算');
const received = ref<string>('准备计算');
const total = ref<string>('');
const installPath = ref(false)
const downloadPath = ref(false)
const start = ref(false);
const operator = ref<string>('准备线路')
let duration = computed(() => Math.floor(percentage.value / 10))





const startDownload = async () => {
  installPath.value = false;
  downloadPath.value = false;
  if (installAddress.value == '请选择安装位置' && downloadAddress.value == '请选择下载位置') {
    installPath.value = true;
    downloadPath.value = true;
    return;
  }
  if (installAddress.value == '请选择安装位置') {
    installPath.value = true;
    return;
  }
  if (downloadAddress.value == '请选择下载位置') {
    downloadPath.value = true;
    return;
  }

  const request = new XMLHttpRequest();
  //request.open('GET', 'https://api.ipify.org?format=json', true);
  request.open('GET', 'https://myip.ipip.net/json', true);
  request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
      let data = JSON.parse(request.responseText);
      operator.value = data.data.location[4] + "线路"
      // console.log(data.data.location[4]);
    }
  };
  request.onerror = function () {
    console.error('Error occurred during the network request');
  };
  request.send();


  start.value = true;
  window.myApi.downloadFile("http://127.0.0.1:8080/download.rar", "download.rar", downloadAddress.value);
  window.myApi.listenDownloadProgress((progress: any, speed: any, remainingTime: any, receivedBytes: any, totalBytes: any) => {
    // console.log(`Progress: ${progress}%`);
    // console.log(`Download Speed: ${speed} KB/s`);
    // console.log(`Estimated Remaining Time: ${remainingTime} seconds`);
    percentage.value = progress; // 更新进度条 
    loadSpeed.value = speed + "MB/s";
    accelerate.value = "+" + (speed * 0.2).toFixed(2) + "MB/s"
    loadRemainingTime.value = formatSeconds(remainingTime);
    received.value = receivedBytes;
    total.value = "MB/" + totalBytes + "MB";
  });
}
function formatSeconds(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = Math.floor(seconds % 60); // 使用 Math.floor 去掉小数部分
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
}


// 使用watch监听installAddress的变化  
watch(installAddress, (newValue, oldValue) => {
  if (newValue != '请选择安装位置') {
    installPath.value = false;
  }
});
watch(downloadAddress, (newValue, oldValue) => {
  if (newValue != '请选择下载位置') {
    downloadPath.value = false;
  }
});




const clickPauseDownload = ref(false)

const pause = () => {
  window.myApi.pauseDownload()
  clickPauseDownload.value = true
}
const resume = () => {
  window.myApi.resumeDownload()
  clickPauseDownload.value = false
}
const toClose = () => {
  window.myApi.windowClose()
}

const cancel = () => {
  // installAddress.value = '请选择安装位置'
  // downloadAddress.value = '请选择下载位置'
  window.myApi.cancelDownload();
  window.myApi.userCanceled((data: any) => {
    console.log(data);
    if (data) {
      I0RD.value = true
      percentage.value = 0
      loadSpeed.value = '准备计算'
      accelerate.value = ''
      loadRemainingTime.value = '准备计算'
      received.value = '准备计算'
      total.value = ''
      installPath.value = false
      downloadPath.value = false
      start.value = false;
      operator.value = '准备线路'
      clickPauseDownload.value = false
    }
  })
}

const throttledStartDownload = throttle(function () {
  startDownload();
}, 500)
const throttledToClose = throttle(function () {
  toClose();
}, 500)
const throttledPause = throttle(function () {
  pause();
}, 500)
const throttledResume = throttle(function () {
  resume();
}, 500)
const throttledCancel = throttle(function () {
  cancel();
}, 500)

</script>
<style scoped>
.radio-but {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 12px;
  height: 12px;
  border: 1px solid black;
}

.radio-box {
  display: flex;
  align-items: center;
}

.home-child {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.line {
  width: 80%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
  position: relative;
}

/* .line.error::after {
  content: '安装位置不能为空';
  color: red;
  font-size: 12px;
  position: absolute;
  top: 20px;
  left: 80px;
}

.line.error {
  position: relative;
} */



.progress {
  width: 80%;
  margin-top: 20px;
}

::v-deep .el-progress-bar__outer {
  border-radius: 0;
  /* 方形 */
}

::v-deep .el-progress-bar__inner {
  border-radius: 0;
  /* 方形 */
}

.progress-text {
  display: flex;
  align-items: center;
  justify-content: end;
  text-align: end;
  width: 80%;
  margin-top: 5px;
}

.line span {
  font-weight: 400;
}


.shake-bottom {
  display: inline-block;
  color: red;
  -webkit-animation: shake-top 0.8s cubic-bezier(0.455, 0.030, 0.515, 0.955) both;
  animation: shake-top 0.8s cubic-bezier(0.455, 0.030, 0.515, 0.955) both;
}

/* ----------------------------------------------
 * Generated by Animista on 2024-8-11 9:18:13
 * Licensed under FreeBSD License.
 * See http://animista.net/license for more info. 
 * w: http://animista.net, t: @cssanimista
 * ---------------------------------------------- */

/**
 * ----------------------------------------
 * animation shake-top
 * ----------------------------------------
 */
@-webkit-keyframes shake-top {

  0%,
  100% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transform-origin: 50% 0;
    transform-origin: 50% 0;
  }

  10% {
    -webkit-transform: rotate(2deg);
    transform: rotate(2deg);
  }

  20%,
  40%,
  60% {
    -webkit-transform: rotate(-4deg);
    transform: rotate(-4deg);
  }

  30%,
  50%,
  70% {
    -webkit-transform: rotate(4deg);
    transform: rotate(4deg);
  }

  80% {
    -webkit-transform: rotate(-2deg);
    transform: rotate(-2deg);
  }

  90% {
    -webkit-transform: rotate(2deg);
    transform: rotate(2deg);
  }
}

@keyframes shake-top {

  0%,
  100% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transform-origin: 50% 0;
    transform-origin: 50% 0;
  }

  10% {
    -webkit-transform: rotate(2deg);
    transform: rotate(2deg);
  }

  20%,
  40%,
  60% {
    -webkit-transform: rotate(-4deg);
    transform: rotate(-4deg);
  }

  30%,
  50%,
  70% {
    -webkit-transform: rotate(4deg);
    transform: rotate(4deg);
  }

  80% {
    -webkit-transform: rotate(-2deg);
    transform: rotate(-2deg);
  }

  90% {
    -webkit-transform: rotate(2deg);
    transform: rotate(2deg);
  }
}


.line button {
  padding: 5px 20px;
  background-color: #05967e;
  color: aliceblue;
  border: none;
  cursor: pointer;
}

.download {
  width: 40%;
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.download button {
  padding: 10px 10px;
  border: none;
  cursor: pointer;
}

.download button:first-child {
  color: aliceblue;
  background-color: rgb(5, 150, 126);
}

.download button:last-child {
  color: black;
  border: 1px solid rgb(210, 210, 210);
}

.finish {
  width: 100%;
  color: aliceblue !important;
  background-color: rgb(5, 150, 126);
}
</style>
